package com.wtwd.device.service;


import com.wtwd.device.model.entity.ThirdPartyUser;
import com.wtwd.device.model.vo.LoginVO;

/**
 * @author zdl
 * @date 2021/11/5 13:18
 */
public interface ThirdPartyUserService {

    /**
     * 1.通过code换取 api调用凭证和用户信息
     * 2.第一次登陆，完成系统注册
     * -判断是否第一次登陆(通过第三方用户的唯一标识)
     * 是:
     * a1.获取第三方用户信息，名字，头像
     * a2.注册用户
     * a3.保存用户信息
     * 否:暂时不做处理
     * 3.完成系统登录
     *
     * @param code
     * @return
     */
    default LoginVO loginTemplate(String code) {
        GetTokenResponseBase tokenResponseBase = getAccessToken(code);
        String userKey = getUserKey(tokenResponseBase);
        ThirdPartyUser user = getUserByUserKey(userKey);
        boolean isFirst = user == null;
        Long userId;
        if (isFirst) {
            ThirdPartyUserInfo userInfo = getUserInfo(tokenResponseBase);
            userId = saveUser(userInfo);
        } else {
            userId = user.getUserId();
        }
        LoginVO loginVO = null;
        if (userId != null) {
            loginVO = doLogin(userId);
            loginVO.setIsFirst(isFirst);
        }
        return loginVO;
    }

    /**
     * 通过IdToken方式进行登陆
     *
     * @param idToken
     * @return
     */
    LoginVO loginForIdTokenTemplate(String idToken);

    GetTokenResponseBase checkIdToken(String idToken);


    ThirdPartyUser getUserByUserKey(String userKey);

    ThirdPartyUserInfo getUserInfo(GetTokenResponseBase getTokenResponseBase);

    /**
     * 返回用户ID
     *
     * @param userInfo
     * @return
     */
    Long saveUser(ThirdPartyUserInfo userInfo);

    String getUserKey(GetTokenResponseBase getTokenResponseBase);


    GetTokenResponseBase getAccessToken(String code);

    LoginVO doLogin(Long userId);

    class GetTokenResponseBase {

        public GetTokenResponseBase(String idToken) {
            this.id_token = idToken;
        }

        String id_token;

        public String getId_token() {
            return id_token;
        }

        public void setId_token(String id_token) {
            this.id_token = id_token;
        }
    }

    class ThirdPartyUserInfo {
        private String userKey;
        private String name;
        private String portrait;

        public String getUserKey() {
            return userKey;
        }

        public void setUserKey(String userKey) {
            this.userKey = userKey;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPortrait() {
            return portrait;
        }

        public void setPortrait(String portrait) {
            this.portrait = portrait;
        }
    }
}
